package com.loong.android.viewpager;

import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class PagerViewAdapter<T> extends PagerBaseAdapter<T> {
    private final static String TAG = PagerViewAdapter.class.getSimpleName();

    private List<ItemInfo> mItemInfoList = new ArrayList<>();
    private boolean mNeedSortItemInfoList = false;

    @Override
    protected boolean checkIsViewFromObject(Object view, Object object) {
        return ((ItemInfo) object).view == view;
    }

    @Override
    protected Object onInstantiateItem(ViewGroup container, int position) {
        if (mItemInfoList.size() > position) {
            ItemInfo itemInfo = mItemInfoList.get(position);
            if (itemInfo != null) return itemInfo;
        }

        View view = (View) getItem(position);

        while (mItemInfoList.size() <= position) {
            mItemInfoList.add(null);
        }

        ItemInfo itemInfo = new ItemInfo(view, position);
        mItemInfoList.set(position, itemInfo);

        ((ViewGroup) container).addView(view);
        return itemInfo;
    }

    @Override
    protected int onGetItemPosition(Object object) {
        ItemInfo itemInfo = (ItemInfo) object;
        View view = itemInfo.view;
        int oldPos = mItemInfoList.indexOf(object);
        if(oldPos >= 0 && getItem(oldPos) != view) {
            int count = getCount();
            int newPos = POSITION_NONE;
            for (int i = 0; i < count; i++) {
                if (getItem(i) != view) continue;
                newPos = i;
                break;
            }
            itemInfo.position = newPos;
            mNeedSortItemInfoList = true;
            return newPos;
        }
        return POSITION_UNCHANGED;
    }

    @Override
    protected void onDestroyItem(ViewGroup container, int position, Object object) {
        ItemInfo itemInfo = (ItemInfo) object;
        View view = itemInfo.view;
        mItemInfoList.set(position, null);
        ((ViewGroup) container).removeView(view);
    }

    private void remakeItemInfoList() {
        if(!mNeedSortItemInfoList) return;
        mNeedSortItemInfoList = false;
        List<ItemInfo> infoList = new ArrayList<>();
        for (ItemInfo itemInfo : mItemInfoList) {
            if(itemInfo == null) continue;
            if(itemInfo.position < 0) continue;
            while (infoList.size() <= itemInfo.position) {
                infoList.add(null);
            }
            infoList.set(itemInfo.position, itemInfo);
        }
        mItemInfoList = infoList;
    }

    @Override
    protected void onFinishUpdate(ViewGroup container) {
        remakeItemInfoList();
    }

    public static class ItemInfo {
        public int position = -1;
        public View view = null;
        public ItemInfo(View view, int position) {
            this.position = position;
            this.view = view;
        }
    }
}
